<?php

namespace app\controller\user\controller;

use app\popo\dto\OrdersPaymentDTO;
use app\popo\dto\OrdersSubmitDTO;
use app\service\OrderService;
use app\support\ResponseHelper;
use DI\Attribute\Inject;
use Shayvmo\WebmanAnnotations\Annotations\GetMapping;
use Shayvmo\WebmanAnnotations\Annotations\PostMapping;
use Shayvmo\WebmanAnnotations\Annotations\PutMapping;
use Shayvmo\WebmanAnnotations\Annotations\RestController;
use support\exception\BusinessException;
use support\Log;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * 用户端订单相关接口
 */
#[RestController("/user/order")]
class OrderController
{
    #[Inject]
    protected OrderService $orderService;

    /**
     * 用户下单
     * @param Request $request
     * @return Response
     */
    #[PostMapping(path: '/submit')]
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            Log::info('用户下单，参数为：', $data);
            
            // 创建 DTO 对象
            $ordersSubmitDTO = new OrdersSubmitDTO();
            $ordersSubmitDTO->setAddressBookId((int)($data['addressBookId'] ?? 0));
            $ordersSubmitDTO->setPayMethod((int)($data['payMethod'] ?? 1));
            $ordersSubmitDTO->setRemark($data['remark'] ?? '');
            $ordersSubmitDTO->setEstimatedDeliveryTime($data['estimatedDeliveryTime'] ?? '');
            $ordersSubmitDTO->setDeliveryStatus((int)($data['deliveryStatus'] ?? 1));
            $ordersSubmitDTO->setTablewareNumber((int)($data['tablewareNumber'] ?? 1));
            $ordersSubmitDTO->setTablewareStatus((int)($data['tablewareStatus'] ?? 1));
            $ordersSubmitDTO->setPackAmount((float)($data['packAmount'] ?? 0));
            $ordersSubmitDTO->setPackAmount((float)($data['packAmount'] ?? 0));
            $ordersSubmitDTO->setAmount((float)($data['amount'] ?? 0));

            // 验证参数 - 暂时注释掉，需要来自 BaseDto 类
            // $ordersSubmitDTO->validateRequired();
            
            $orderSubmitVO = $this->orderService->submitOrder($ordersSubmitDTO);
            return ResponseHelper::successJson($orderSubmitVO->toArray());
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('用户下单异常：' . $e->getMessage());
            return ResponseHelper::failJson('下单失败');
        }
    }

    /**
     * 订单支付
     * @param Request $request
     * @return Response
     */
    #[PutMapping(path: '/payment')]
    public function payment(Request $request): Response
    {
        try {
            $data = $request->post();
            Log::info('订单支付：', $data);
            
            // 创建 DTO 对象
            $ordersPaymentDTO = new OrdersPaymentDTO();
            $ordersPaymentDTO->setOrderNumber($data['orderNumber'] ?? '');
            $ordersPaymentDTO->setPayMethod((int)($data['payMethod'] ?? 1));
            
            // 验证参数 - 暂时注释掉，需要来自 BaseDto 类
            // $ordersPaymentDTO->validateRequired();
            
            $orderPaymentVO = $this->orderService->payment($ordersPaymentDTO);
            Log::info('生成预支付交易单：', $orderPaymentVO->toArray());
            
            return ResponseHelper::successJson($orderPaymentVO->toArray());
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('订单支付异常：' . $e->getMessage());
            return ResponseHelper::failJson('支付失败');
        }
    }

    /**
     * 历史订单查询
     * @param Request $request
     * @return Response
     */
    #[GetMapping(path: '/historyOrders')]
    public function historyOrders(Request $request): Response
    {
        try {
            $page = (int)($request->get('page', 1));
            $pageSize = (int)($request->get('pageSize', 10));
            $status = $request->get('status');
            $status = $status !== null && $status !== '' ? (int)$status : null;
            
            $pageResult = $this->orderService->pageQuery4User($page, $pageSize, $status);
            return ResponseHelper::successJson($pageResult->toArray());
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('历史订单查询异常：' . $e->getMessage());
            return ResponseHelper::failJson('查询失败');
        }
    }

    /**
     * 查询订单详情
     * @param int $id
     * @return Response
     */
    #[GetMapping(path: '/orderDetail/{id}')]
    public function orderDetail(int $id): Response
    {
        try {
            if (!$id) {
                return ResponseHelper::failJson('订单ID不能为空');
            }
            
            $orderVO = $this->orderService->details($id);
            return ResponseHelper::successJson($orderVO->toArray());
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('查询订单详情异常：' . $e->getMessage());
            return ResponseHelper::failJson('查询失败');
        }
    }

    /**
     * 用户取消订单
     * @param int $id
     * @return Response
     */
    #[PutMapping(path: '/cancel/{id}')]
    public function cancel(int $id): Response
    {
        try {
            if (!$id) {
                return ResponseHelper::failJson('订单ID不能为空');
            }
            
            $this->orderService->userCancelById($id);
            return ResponseHelper::successJson();
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('取消订单异常：' . $e->getMessage());
            return ResponseHelper::failJson('取消失败');
        }
    }

    /**
     * 再来一单
     * @param int $id
     * @return Response
     */
    #[PostMapping(path: '/repetition/{id}')]
    public function repetition(int $id): Response
    {
        try {
            if (!$id) {
                return ResponseHelper::failJson('订单ID不能为空');
            }
            
            $this->orderService->repetition($id);
            return ResponseHelper::successJson();
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('再来一单异常：' . $e->getMessage());
            return ResponseHelper::failJson('操作失败');
        }
    }

    /**
     * 客户催单
     * @param int $id
     * @return Response
     */
    #[GetMapping(path: '/reminder/{id}')]
    public function reminder(int $id): Response
    {
        try {
            if (!$id) {
                return ResponseHelper::failJson('订单ID不能为空');
            }
            
            $this->orderService->reminder($id);
            return ResponseHelper::successJson();
        } catch (BusinessException $e) {
            return ResponseHelper::failJson($e->getMessage());
        } catch (\Exception $e) {
            Log::error('客户催单异常：' . $e->getMessage());
            return ResponseHelper::failJson('催单失败');
        }
    }
}